/**
 * 发票袋设置详情
 */
import React, { Component } from 'react';
import { connect } from 'react-redux'
import { messages } from "share/common";
import { Form, Radio, InputNumber, Input, Checkbox, Select, Icon, Popover } from 'antd'
import InputLanguage from 'components/template/input-language'
import Chooser from 'components/chooser'
import WrapFormItem from 'components/wrap-form-item'
import CompactInput from 'components/compact-input'
import SlideFrameContent from '../slide-frame-content'
import requestAndExpenseService from '../request-and-expense-settings.service'
import subsetImg from 'images/subset.png'
import chooserData from 'share/chooserData'
import 'styles/request-and-expense-settings/invoice-bag.scss'

const RadioGroup = Radio.Group;
const CheckboxGroup = Checkbox.Group;
const { Option } = Select;

class InvoiceBagSettingDetail extends Component {

  record = this.props.params.record || {};

  priorityInfo = {
    top: (this.props.authPolicyAll || this.record.id) ? 'TENANT' : 'COMPANY',
    disabled: !!this.record.id,
    value: this.record.id ? {
      levelCode: this.record.levelCode,
      levelOrgId: this.record.levelOrgId,
      levelOrgName: this.record.levelOrgName,
      distribution: {
        companies: this.record.companyInfos
      }
    } : {
      levelCode: this.props.authPolicyAll ? 'TENANT' : 'COMPANY',
      levelOrgId: this.props.authPolicyAll ? this.props.tenant.id : this.props.company.id,
      levelOrgName: this.props.authPolicyAll ? this.props.tenant.tenantName : this.props.company.name,
    }
  };

  expenseStatusOptions = [
    { label: messages('expense-15.key187')/*编辑中*/, value: 1001 },
    {label: messages('expense-15.key120')/*审批中*/, value: 1002},
    {label: messages('expense-15.key121')/*已通过*/, value: 1003},
    {label: messages('expense-15.key122')/*审核通过*/, value: 1004},
    {label: messages('expense-15.key123')/*待付款*/, value: 1007},
    {label: messages('expense-15.key124')/*付款中*/, value: 1008},
    {label: messages('expense-15.key125')/*已付款*/, value: 1005}
  ];

  expenseLabelOptions = [
    {label: messages('expense-15.key126')/*全部标签*/, value: '1'},
    {label: messages('expense-15.key127')/*部分标签*/, value: '2'},
  ];

  associatedTypeOptions = [{
    key: 0,
    title: messages('expense-15.key128')/*不启用*/,
    description: messages('expense-15.key129')/*报销单页面不可关联发票袋，只可在发票袋页面关联报销单*/
  }, {
    key: 2,
    title: messages('expense-15.key130')/*启用，强制关联发票袋*/,
    description: (
      <div>
        1. {messages('expense-15.key131')/*报销单页面可关联发票袋，并且必须关联发票袋才可提交发票袋*/}
        <br/>
        2. {messages('expense-15.key132')/*当发票袋设置只可关联1个报销单，且当报销单到达本页面设置的条件时，自动提交发票袋；当发票袋设置可关联多个报销单，则在报销单提交关联发票袋页面，员工可对发票袋开启自动提交*/}
        <br/>
        {messages('expense-15.key133')/*注：请在审批流中配置【打印】节点，则发票袋中所有单据经过打印节点后，会自动提交发票袋，并通知员工提交成功／失败*/}
      </div>
    )
  }];

  promptInfoOptions = [
    {label: messages('common.yes')/*是*/, value: true},
    {label: messages('common.no')/*否*/, value: false},
  ];

  formRelationOptions = [
    {label: messages('common.all')/*全部*/, value: 1000},
    {label: messages('expense-15.key134')/*部分*/, value: 1001},
    {label: messages('expense-15.key128')/*不启用*/, value: 1002}
  ];

  formItemLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 17, offset: 1 },
  };

  formList1 = [{
    id: 'maxLength',
    label: messages('expense-15.key116')/*位数限制*/,
    initialValue: this.record.maxLength,
    rules: [{
      required: true,
      message: messages('expense-15.key32')/*请输入temp2*/
    }],
    component: (
      <InputNumber
        min={1}
        max={99}
        step={1}
        placeholder={messages('expense-15.key135')/*请输入正整数，上限为99*/}
        disabled={this.record.readOnly || !!this.record.id}
      />
    )
  }, {
    id: 'preFix',
    label: messages('expense-15.key115')/*首位限制*/,
    initialValue: this.record.preFix,
    rules: [{
      required: true,
      message: messages('expense-15.key32')/*请输入temp2*/
    }, {
      max: 20,
      message: messages('common.max.characters.length',{arg1: 20})/*最多输入{arg1}个字符*/
    }, {
      validator: (item, value, callback) => {
        let params = { preFix: value };
        this.record.id && (params.id = this.record.id);
        requestAndExpenseService.checkPrefix(params).then(res => {
          if (!res.data.passFlag) {
            callback(res.data.message);
          } else {
            callback();
          }
        }).catch(() => {
          callback();
        })
      }
    }],
    component: (
      <Input
        placeholder={messages('expense-15.key136')/*最多输入20个字符*/}
        disabled={this.record.readOnly || !!this.record.id}
      />
    )
  }];

  formList3 = [{
    id: 'showInstructionsFlag',
    label: messages('expense-15.key137')/*是否启用*/,
    extra: messages('expense-15.key138')/*启用后员工可在发票袋界面查看说明内容*/,
    initialValue: this.record.showInstructionsFlag || false,
    component: (
      <RadioGroup
        options={this.promptInfoOptions}
        disabled={this.record.readOnly}
        onChange={e => e.target.value ? this.formList3.push(...this.promptFormList) : this.formList3.splice(1, 2)}
      />
    )
  }];

  promptFormList = [{
    id: 'title',
    label: messages('expense-15.key139')/*标题*/,
    initialValue: this.record.id ? {
      name: this.record.title,
      i18n: this.record.i18n ? this.record.i18n.title : []
    } : undefined,
    component: (
      <InputLanguage
        maxLength={[{ length: '60', language: 'zh_cn' }, { length: '180', language: 'en' }]}
        placeholder={messages('common.please.input')/*请输入*/}
        disabled={this.record.readOnly}
      />
    )
  }, {
    id: 'content',
    label: messages('expense-15.key140')/*描述内容*/,
    initialValue: this.record.id ? {
      name: this.record.content,
      i18n: this.record.i18n ? this.record.i18n.content : []
    } : undefined,
    rules: [{
      required: true,
      message: messages('expense-15.key32')/*请输入temp2*/
    }, {
      validator: (item, value, callback) => {
        if (value && !value.name) {
          callback(messages('expense-15.key32')/*请输入temp2*/)
        }
        callback();
      }
    }],
    component: (
      <InputLanguage
        textArea
        maxLength={[{ length: '600', language: 'zh_cn' }, { length: '1800', language: 'en' }]}
        placeholder={messages('common.please.input')/*请输入*/}
        extraProps={{ rows: 4 }}
        disabled={this.record.readOnly}
      />
    )
  }];

  state = {
    needRefresh: false,
    priority: {
      levelCode: this.record.levelCode || (this.props.authPolicyAll ? 'TENANT' : 'COMPANY'),
      companyOID: this.record.companyOID
    },
    formList2: [{
      id: 'expenseSizeRange',
      label: messages('expense-15.key141')/*报销单数量*/,
      rules: [{
        required: true,
        message: messages('expense-15.key32')/*请输入temp2*/
      }, {
        validator: (item, value, callback) => {
          if (!value.minExpenseReportSize) {
            callback(messages('expense-15.key142')/*请输入关联报销单数量的最小值*/);
          }
          if (!value.maxExpenseReportSize) {
            callback(messages('expense-15.key143')/*请输入关联报销单数量的最大值*/);
          }
          if (value.minExpenseReportSize > value.maxExpenseReportSize) {
            callback(messages('expense-15.key144')/*关联报销单数量的最大值必须大于等于最小值*/);
          }
          callback();
        }
      }],
      initialValue: {
        minExpenseReportSize: this.record.minExpenseReportSize || 1,
        maxExpenseReportSize: this.record.maxExpenseReportSize || 100
      },
      component: (
        <WrapFormItem>
          {(onChange, value) => (
            <div className="expense-number">
              <div className='num-min'>{messages('expense-15.key145')/*最小*/}</div>
              <InputNumber
                value={value.minExpenseReportSize}
                min={1}
                step={1}
                disabled={this.record.readOnly}
                onChange={minExpenseReportSize => onChange({ minExpenseReportSize })}
              />
              <div className='inline-box'>-</div>
              <div className='num-max'>{messages('expense-15.key146')/*最大*/}</div>
              <InputNumber
                value={value.maxExpenseReportSize}
                min={1}
                max={100}
                step={1}
                disabled={this.record.readOnly}
                onChange={maxExpenseReportSize => onChange({ maxExpenseReportSize })}
              />
            </div>
          )}
        </WrapFormItem>
      )
    }, {
      id: 'statuses',
      label: messages('expense-15.key147')/*报销单状态*/,
      formItemLayout: this.formItemLayout,
      initialValue: this.record.statuses || [1003],
      rules: [{
        required: true,
        message: messages('common.select')/*请选择*/
      }],
      component: <CheckboxGroup options={this.expenseStatusOptions} disabled={this.record.readOnly}/>
    }, {
      id: 'labels',
      label: (
        <span>
          {messages('expense-15.key148')/*报销单标签包含*/}
          <Popover content={messages('expense-15.key149')/*采用工作流配置多级审核时，建议在审核前配置【打印】节点，并且发票袋规则配置：报销单标签包含【可交单】且报销单状态为审批中*/}>
            <Icon type="info-circle-o" style={{ marginLeft: 5, cursor: 'pointer' }} />
          </Popover>
        </span>
      ),
      rules: [{
        required: true,
        message: messages('common.select')/*请选择*/
      }, {
        validator: (item, value, callback) => {
          if (value.labelsTag === '2' && !(value.labels && value.labels.length)) {
            callback(messages('expense-15.key150')/*请选择报销单标签*/)
          }
          callback();
        }
      }],
      initialValue: {
        labelsTag: (this.record.labels && this.record.labels.length || !this.record.id) ? '2' : '1',
        labels: this.record.id ? this.record.labels : this.props.params.defaultLabel
      },
      component: (
        <WrapFormItem>
          {(onChange, values) => (
            <CompactInput>
              <Select
                style={{ width: '100%' }}
                value={values.labelsTag}
                disabled={this.record.readOnly}
                className="select-expense-tag"
                dropdownStyle={{ minWidth: 100 }}
                onChange={labelsTag => onChange({ labelsTag })}
              >
                {this.expenseLabelOptions.map(item => <Option key={item.value}>{item.label}</Option>)}
              </Select>
              <Chooser
                type='select_expense_labels'
                labelKey='name'
                valueKey='id'
                placeholder={messages('expense-15.key151')/*通用*/}
                showNumber={values.labelsTag === '2'}
                value={values.labelsTag === '1' ? undefined : values.labels}
                disabled={values.labelsTag === '1' || this.record.readOnly}
                onChange={labels => onChange({ labels })}
              />
            </CompactInput>
          )}
        </WrapFormItem>
      )
    }, {
      id: 'formRelationConfig',
      label: messages('expense-15.key152')/*可关联的表单范围*/,
      formItemLayout: this.formItemLayout,
      component: (
        <span className="invoice-bag-setting-form-range-tip">
          {messages('expense-15.key153')/*发票袋可关联下述【强制关联表单】和【不强制关联表单】中配置的表单*/}
        </span>
      )
    }, {
      id: 'forcedRelatedForm',
      label: (
        <span>
          <img src={subsetImg} className="invoice-bag-setting-subset" />
          {messages('expense-15.key154')/*强制关联*/}
          <Popover content={(
            <div>
              1. {messages('expense-15.key155')/*不启用，则报销单提交时不可关联发票袋*/} <br/>
              2. {messages('expense-15.key156')/*当配置全部／部分，则所选表单对应报销单必须关联发票袋才可提交。当发票袋设置只可关联1个报销单，则默认自动提交发票袋；当发票袋设置可关联多个报销单，则在报销单提交关联发票袋页面，员工可对发票袋开启自动提交 （注：请在审批流中配置【打印】节点，则发票袋中所有单据经过打印节点后，会自动提交发票袋，并通知员工提交成功／失败*/} <br/>
              3. {messages('expense-15.key157')/*优先级：【强制关联表单】大于【不强制关联表单】，不在2者配置内的表单视为不可关联发票袋。即当一个表单同时存在于强制和不强制关联，则视为强制关联；如果有表单同时不存在于强制和不强制关联，则表示该表单不可关联发票袋*/}
            </div>
          )}>
            <Icon type="info-circle-o" style={{ marginLeft: 5, cursor: 'pointer' }} />
          </Popover>
        </span>
      ),
      rules: [{
        required: true,
        message: messages('common.select')/*请选择*/
      }, {
        validator: (item, value, callback) => {
          if (+value.forcedRelatedType === 1001 && !(value.forcedRelatedFormIDs && value.forcedRelatedFormIDs.length)) {
            callback(messages('expense-15.key158')/*请选择表单*/)
          }
          callback();
        }
      }],
      initialValue: {
        forcedRelatedType: this.record.formRelationConfig ? this.record.formRelationConfig.forcedRelatedType : 1002,
        forcedRelatedFormIDs: this.record.formRelationConfig ? this.record.formRelationConfig.forcedRelatedFormIDs : [],
        forcedRelatedFormNames: this.record.formRelationConfig ? this.record.formRelationConfig.forcedRelatedFormNames : []
      },
      component: (
        <WrapFormItem>
          {(onChange, values) => {
            const { priority } = this.state;
            const isCompany = priority && priority.levelCode === 'COMPANY';
            let type = String(values.forcedRelatedType);
            let listExtraParams = { entityTypeList: 1002, valid: true };
            if (isCompany) {
              listExtraParams = { formTypeList: [3001, 3002, 3003], companyOID: priority.companyOID }
            }
            let chooserItem = isCompany ? chooserData['select_form'] : chooserData['available_forms'];
            let searchForm = [{
              type: 'input',
              id: isCompany ? 'keyword' : 'formName',
              label: messages('expense-15.key159')/*表单名称*/
            }];
            chooserItem.title = messages('expense-15.key160')/*选择表单*/;
            chooserItem.searchForm = searchForm;
            chooserItem.key = 'id';
            let chooserValue = [];
            values.forcedRelatedFormIDs && values.forcedRelatedFormIDs.map((id, index) =>
              chooserValue.push({ id, formName: values.forcedRelatedFormNames[index] })
            );
            return (
              <CompactInput>
                <Select
                  style={{ width: '100%' }}
                  value={type}
                  disabled={this.record.readOnly}
                  dropdownStyle={{ minWidth: 90 }}
                  onChange={forcedRelatedType => onChange({ forcedRelatedType })}
                >
                  {this.formRelationOptions.map(item => <Option key={item.value}>{item.label}</Option>)}
                </Select>
                <Chooser
                  selectorItem={chooserItem}
                  labelKey='formName'
                  valueKey='id'
                  onlyNeed='id'
                  placeholder={type === '1000' ? messages('expense-15.key151')/*通用*/ :
                    type === '1001' ? messages('common.select')/*请选择*/ : messages('expense-15.key128')/*不启用*/}
                  value={type === '1001' ? chooserValue : undefined}
                  disabled={
                    type !== '1001' ||
                    this.record.readOnly ||
                    !priority ||
                    (priority.levelCode === 'COMPANY' && !priority.companyOID)
                  }
                  listExtraParams={listExtraParams}
                  onChange={forcedRelatedFormIDs => onChange({ forcedRelatedFormIDs })}
                />
              </CompactInput>
            )
          }}
        </WrapFormItem>
      )
    }, {
      id: 'unforcedRelatedForm',
      label: (
        <span style={{ marginLeft: 19 }}>
          {messages('expense-15.key161')/*不强制关联*/}
          <Popover content={messages('expense-15.key162')/*所选表单可在发票袋子应用进行关联报销单 */}>
            <Icon type="info-circle-o" style={{ marginLeft: 5, cursor: 'pointer' }} />
          </Popover>
        </span>
      ),
      rules: [{
        required: true,
        message: messages('common.select')/*请选择*/
      }, {
        validator: (item, value, callback) => {
          if (+value.unforcedRelatedType === 1001 && !(value.unforcedRelatedFormIDs && value.unforcedRelatedFormIDs.length)) {
            callback(messages('expense-15.key158')/*请选择表单*/)
          }
          callback();
        }
      }],
      initialValue: {
        unforcedRelatedType: this.record.formRelationConfig ? this.record.formRelationConfig.unforcedRelatedType : 1000,
        unforcedRelatedFormIDs: this.record.formRelationConfig ? this.record.formRelationConfig.unforcedRelatedFormIDs : [],
        unforcedRelatedFormNames: this.record.formRelationConfig ? this.record.formRelationConfig.unforcedRelatedFormNames : []
      },
      component: (
        <WrapFormItem>
          {(onChange, values) => {
            const { priority } = this.state;
            const isCompany = priority && priority.levelCode === 'COMPANY';
            let type = String(values.unforcedRelatedType);
            let listExtraParams = { entityTypeList: 1002, valid: true };
            if (isCompany) {
              listExtraParams = { formTypeList: [3001, 3002, 3003], companyOID: priority.companyOID }
            }
            let chooserItem = isCompany ? chooserData['select_form'] : chooserData['available_forms'];
            let searchForm = [{
              type: 'input',
              id: isCompany ? 'keyword' : 'formName',
              label: messages('expense-15.key159')/*表单名称*/
            }];
            chooserItem.title = messages('expense-15.key160')/*选择表单*/;
            chooserItem.searchForm = searchForm;
            chooserItem.key = 'id';
            let chooserValue = [];
            values.unforcedRelatedFormIDs && values.unforcedRelatedFormIDs.map((id, index) =>
              chooserValue.push({ id, formName: values.unforcedRelatedFormNames[index] })
            );
            return (
              <CompactInput>
                <Select
                  style={{ width: '100%' }}
                  value={type}
                  disabled={this.record.readOnly}
                  dropdownStyle={{ minWidth: 90 }}
                  onChange={unforcedRelatedType => onChange({ unforcedRelatedType })}
                >
                  {this.formRelationOptions.map(item => <Option key={item.value}>{item.label}</Option>)}
                </Select>
                <Chooser
                  selectorItem={chooserItem}
                  labelKey='formName'
                  valueKey='id'
                  onlyNeed='id'
                  placeholder={type === '1000' ? messages('expense-15.key151')/*通用*/ :
                    type === '1001' ? messages('common.select')/*请选择*/ : messages('expense-15.key128')/*不启用*/}
                  value={type === '1001' ? chooserValue : undefined}
                  disabled={
                    type !== '1001' ||
                    this.record.readOnly ||
                    !priority ||
                    (priority.levelCode === 'COMPANY' && !priority.companyOID)
                  }
                  listExtraParams={listExtraParams}
                  onChange={unforcedRelatedFormIDs => onChange({ unforcedRelatedFormIDs })}
                />
              </CompactInput>
            )
          }}
        </WrapFormItem>
      )
    }],
  };

  componentDidMount() {
    if (this.record.showInstructionsFlag) {
      this.formList3.push(...this.promptFormList)
    }
  }

  dealParams = values => {
    values.i18n = {};
    values.labels = values.labels.labelsTag === '2' ? values.labels.labels : [];
    if (values.expenseSizeRange) {
      values.minExpenseReportSize = values.expenseSizeRange.minExpenseReportSize;
      values.maxExpenseReportSize = values.expenseSizeRange.maxExpenseReportSize;
      delete values.expenseSizeRange;
    }
    if (values.title) {
      values.i18n.title = values.title.i18n;
      values.title = values.title.name;
    }
    if (values.content) {
      values.i18n.content = values.content.i18n;
      values.content = values.content.name;
    }
    values.formRelationConfig = {
      forcedRelatedType: +values.forcedRelatedForm.forcedRelatedType,
      forcedRelatedFormIDs: values.forcedRelatedForm.forcedRelatedFormIDs,
      unforcedRelatedType: +values.unforcedRelatedForm.unforcedRelatedType,
      unforcedRelatedFormIDs: values.unforcedRelatedForm.unforcedRelatedFormIDs
    };
    delete values.forcedRelatedForm;
    delete values.unforcedRelatedForm;
    values.id = this.record.id;
    return values;
  };

  render() {
    const { formList2 } = this.state;
    return (
      <SlideFrameContent
        disabled={this.record.readOnly}
        priorityInfo={this.priorityInfo}
        enabled={this.record.id ? this.record.enabled : true}
        formInfo={[
          {title: messages('expense-15.key163')/*编码规则设置*/, list: this.formList1},
          {title: messages('expense-15.key164')/*关联报销单设置*/, list: formList2},
          {title: messages('expense-15.key165')/*说明文字*/, list: this.formList3}
        ]}
        service={requestAndExpenseService.saveBagSetting}
        dealParams={this.dealParams}
        close={this.props.close}
        onPriorityChange={priority => this.setState({ priority })}
      />
    )
  }

}

function mapStateToProps(state) {
  return {
    authPolicyAll: state.main.authPolicyAll,
    company: state.login.company,
    tenant: state.login.tenant,
  }
}

const WrappedInvoiceBagSettingDetail = Form.create()(InvoiceBagSettingDetail);

export default connect(mapStateToProps)(WrappedInvoiceBagSettingDetail);
